'use strict';

import { hexToLab, deltaE2000 } from './deltaE2000.js';

const ICONS = {"play": "<svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\"><path d=\"M8 5v14l11-7z\" fill=\"currentColor\"/></svg>", "star": "<svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\"><path d=\"M12 .587l3.668 7.431L24 9.748l-6 5.847 1.417 8.263L12 19.771 4.583 23.858 6 15.595 0 9.748l8.332-1.73L12 .587z\" fill=\"currentColor\"/></svg>", "download": "<svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\"><path d=\"M5 20h14v-2H5v2zm7-18l-5 5h3v6h4V7h3l-5-5z\" fill=\"currentColor\"/></svg>", "cart": "<svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\"><path d=\"M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zm10 0c-1.1 0-1.99.9-1.99 2S15.9 22 17 22s2-.9 2-2-.9-2-2-2zM7.16 14h9.45c.75 0 1.41-.41 1.75-1.03L22 7H6.31L5.21 4H1v2h2l3.6 7.59-1.35 2.45C4.52 17.37 5.48 19 7 19h12v-2H7l1.1-2h8.45c.75 0 1.41-.41 1.75-1.03l2.5-4.5H7.16l-.83-1.5h13.42v-2H5.21L7.16 14z\" fill=\"currentColor\"/></svg>"};

function ensureResultContainer() {
  let host = document.querySelector('#rt-color-results');
  if (!host) {
    // Try to place right below palette area
    // 1) below an element likely to be the palette
    const palette = document.querySelector('#palette, .palette, .color-palette, [data-role="palette"]');
    host = document.createElement('section');
    host.id = 'rt-color-results';
    host.innerHTML = `
      <div class="rt-list">
        <div class="rt-header">
          <div>标题</div>
          <div>标签</div>
          <div>BPM</div>
          <div>时长</div>
          <div>授权</div>
          <div>操作</div>
        </div>
        <div id="rt-list-body"></div>
      </div>`;
    if (palette && palette.parentNode) {
      palette.parentNode.insertBefore(host, palette.nextSibling);
    } else {
      document.body.appendChild(host);
    }
  }
  return host;
}

function removeSearchButton() {
  const btn = document.querySelector('#searchByColorBtn, .search-by-color-btn');
  if (btn) btn.remove();
}

function listTracks(tracks) {
  ensureResultContainer();
  const body = document.querySelector('#rt-list-body');
  if (!body) return;
  body.innerHTML = '';
  tracks.forEach((t) => {
    const row = document.createElement('div');
    row.className = 'rt-row';

    const cTitle = document.createElement('div');
    cTitle.className = 'rt-title';

    const play = document.createElement('button'); play.className='rt-play'; play.innerHTML = ICONS.play; play.title='播放/暂停';
    play.addEventListener('click', (e) => e.stopPropagation());

    const dot = document.createElement('button'); dot.className='rt-color-dot'; dot.style.background = t.color || '#999';
    dot.title = '以此曲目主色重新匹配';
    dot.addEventListener('click', (e) => { e.stopPropagation(); if (t.color) triggerMatch(t.color); });

    const box = document.createElement('div'); box.className='rt-title-text';
    const name = document.createElement('div'); name.className='rt-name'; name.textContent=t.title || '-';
    const artist = document.createElement('div'); artist.className='rt-artist'; artist.textContent=t.artist || '';
    const de = document.createElement('span'); de.className='rt-de'; de.textContent = (typeof t.deltaE==='number') ? `ΔE {t.deltaE.toFixed(1)}`.replace('{t.deltaE.toFixed(1)}', t.deltaE.toFixed(1)) : '';
    const inline = document.createElement('div'); inline.style.display='flex'; inline.style.alignItems='center'; inline.style.gap='8px';
    inline.appendChild(dot); inline.appendChild(box); inline.appendChild(de);
    box.appendChild(name); box.appendChild(artist);

    cTitle.appendChild(play); cTitle.appendChild(inline);

    const cTags = document.createElement('div'); cTags.className='rt-tags';
    (t.tags || []).forEach(tag => { const el=document.createElement('span'); el.className='rt-tag'; el.textContent=tag; cTags.appendChild(el); });

    const cBpm = document.createElement('div'); cBpm.textContent = t.bpm ?? '-';
    const cDur = document.createElement('div'); cDur.textContent = t.duration ?? '-';
    const cLic = document.createElement('div'); cLic.textContent = t.license ?? '';

    const cAct = document.createElement('div'); cAct.className='rt-actions';
    ['star','download','cart'].forEach(k=>{ const b=document.createElement('button'); b.className='rt-icon-btn'; b.innerHTML=ICONS[k]; cAct.appendChild(b); });

    row.appendChild(cTitle);
    row.appendChild(cTags);
    row.appendChild(cBpm);
    row.appendChild(cDur);
    row.appendChild(cLic);
    row.appendChild(cAct);

    body.appendChild(row);
  });
}

function computeMatches(hex, pool) {
  const base = hexToLab(hex);
  return pool.map(t => ({ ...t, deltaE: (t.color ? deltaE2000(base, hexToLab(t.color)) : 999) }))
             .sort((a,b) => a.deltaE - b.deltaE);
}

function getSensitivity() {
  const slider = document.querySelector('#deltaESlider, #deSlider, [data-role="deltaE-slider"]');
  const v = slider ? Number(slider.value || slider.getAttribute('value') || 30) : 30;
  return isNaN(v) ? 30 : v;
}

function triggerMatch(hex) {
  // 数据来源优先级：window.MUSIC_DATA > window.getMusicPool()
  let pool = [];
  if (Array.isArray(window.MUSIC_DATA)) pool = window.MUSIC_DATA;
  else if (typeof window.getMusicPool === 'function') pool = window.getMusicPool() || [];

  // 兼容：若页面仅有三条“烈焰之心/桃气泡/治愈手札”，也会按你的提供值渲染
  if (!pool || !pool.length) {
    pool = [
      { title:'烈焰之心', artist:'RT Studio', color:'#FF7D7D', bpm:100, duration:'00:16', tags:['色彩','灵感'], license:'商用:全球' },
      { title:'桃气泡',   artist:'RT Studio', color:'#FF8BD7', bpm:107, duration:'00:23', tags:['色彩','灵感'], license:'商用:全球' },
      { title:'治愈手札', artist:'RT Studio', color:'#FFC6A7', bpm:114, duration:'00:30', tags:['色彩','灵感'], license:'商用:全球' },
    ];
  }

  const matches = computeMatches(hex, pool);
  const sens = getSensitivity();
  const filtered = matches.filter(m => m.deltaE <= sens);
  listTracks(filtered.length ? filtered : matches);
}

function wirePalette() {
  // 绑定 HEX 输入、色块、吸管等（尽量不破坏原有逻辑）
  const hexInput = document.querySelector('#hexInput, #colorHex, input[name="hex"]');
  const swatches = document.querySelectorAll('.swatch, .color-swatch, [data-role="swatch"]');
  const eyedropperBtn = document.querySelector('#eyedropperBtn, .eyedropper-btn');
  const slider = document.querySelector('#deltaESlider, #deSlider, [data-role="deltaE-slider"]');

  if (hexInput) hexInput.addEventListener('change', () => { const v=hexInput.value.trim(); if (/^#?[0-9a-fA-F]{6}$/.test(v)) triggerMatch(v.startsWith('#')?v:'#'+v); });
  if (swatches && swatches.length) swatches.forEach(el => el.addEventListener('click', () => { const s=getComputedStyle(el).backgroundColor; }));
  if (eyedropperBtn && window.EyeDropper) eyedropperBtn.addEventListener('click', async ()=>{ try{ const ed=new EyeDropper(); const r=await ed.open(); triggerMatch(r.sRGBHex); }catch(e){} });
  if (slider) slider.addEventListener('input', () => { const cur = window.__rt_last_hex || '#EE7D7D'; triggerMatch(cur); });
}

// 暴露API，便于现有代码直接使用
window.RTColorMatch = { triggerMatch, listTracks };

(function boot() {
  removeSearchButton();
  ensureResultContainer();
  const initHex = '#EE7D7D';
  window.__rt_last_hex = initHex;
  triggerMatch(initHex);
})();
